<script setup>
import { computed, inject, onMounted, ref } from "vue";
//图标
import { IconArrowLeft, IconTopCircle, IconHomeAlt, IconCart, IconUser, IconTriangleDown, IconTriangleUp, IconCaretLeft, IconCaretRight } from '../icon/index.js'
import DlLoading from '../components/DlLoading.vue'
import { DlMessageBox } from '../util/messagebox.js'
import ProductBox from '../components/ProductBox.vue'

//引入 api
import { findMiaoShaDataFun, getProductsByMiaoShaIdFun } from '../api/miaosha.js'
import { addToCartFun } from '../api/cart.js'

//主菜单核心
const menuCore = inject('menuCore');
//返回
function doGoBack() {
    menuCore.back();
}

//秒杀活动
const msLoading = ref(false);
const miaoShaArr = ref([]);
function doLoadMiaoShaData() {
    msLoading.value = true;
    //获取秒杀活动
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
            for(let i=1;i<13;i++) {
                dataArr.push({id: i, name: '活动-'+i, expireTime: Date.now() + 1800000 + (~~(Math.random()*1000000)) });
            }

            //成功后执行以下操作
            miaoShaArr.value = dataArr;
            msLoading.value = false;
            if(miaoShaArr.value.length > 0) {//展示初始的活动商品
                doSelectMiaoSha(miaoShaArr.value[0], 0);
            }
        }, 1000);
    } else {
        //请求api
        findMiaoShaDataFun().then((result)=>{
            console.log('findMiaoShaDataFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);

                //成功后执行以下操作
                miaoShaArr.value = result.data;                
                if(miaoShaArr.value.length > 0) {//展示初始的活动商品
                    doSelectMiaoSha(miaoShaArr.value[0], 0);
                }
            } else {
                DlMessageBox.error(result.msg);
            }
            msLoading.value = false;
        });
    }
}
//秒杀活动选择
const currentMiaoSha = ref();
function doSelectMiaoSha(ms, index) {
    msIndex = index;
    if(!ms.selected){
        miaoShaArr.value.forEach(m=>{ m.selected=false });
        ms.selected = true;
        currentMiaoSha.value = ms;
        
        clearInterval(endTimer.value);//清空旧定时器
        countDownTime();//初始化
        endTimer.value = setInterval(countDownTime, 1000);//启动

        //加载对应的秒杀商品
        productArr.value = [];
        currentPageNum.value = 1;
        pages.value = 0;
        doLoadProductData();
    }
}

const miaoShaListRef = ref();
let msIndex = 0;//展示位置对应的元素索引
function doMoveLeft() {
    let t = miaoShaListRef.value;
    if(t) {
        if(msIndex <= 0) {
            return;
        }
        msIndex--;
        //移动
        let carr = t.children;
        let left = carr[msIndex].offsetLeft;
        t.scrollTo({left: left, behavior: 'smooth'});
        //选中活动
        doSelectMiaoSha(miaoShaArr.value[msIndex], msIndex);
    }
}
function doMoveRight(){
    let t = miaoShaListRef.value;
    if(t) {
        if(msIndex >= miaoShaArr.value.length-1) {
            return;
        }
        msIndex++;
        //移动
        let carr = t.children;
        let left = carr[msIndex].offsetLeft;
        t.scrollTo({left: left, behavior: 'smooth'});
        //选中活动
        doSelectMiaoSha(miaoShaArr.value[msIndex], msIndex);
    }
}

//加载秒杀商品
const productArr = ref([]);
const currentPageNum = ref(1);
const pageSize = 5;
const pages = ref(0);
const productLoading = ref(false);
const noMoreData = ref(false);//是否没有更多数据
function doLoadProductData() {
    productLoading.value = true;
    //加载对应的秒杀商品
    let params = {
        miaoShaId: currentMiaoSha.value.id,
        pageNum: currentPageNum.value,
        pageSize: pageSize
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
            let key = dataArr.length + 1;
            dataArr.push({id: key, title: '测试-'+key, image: './product.jpg', price: 9999.99, type:['红色','绿色','蓝色'], status:1});
            for(let i=1;i<5; i++) {
                dataArr.push({id: i+key, title: '测试测试测试测试-'+(i+key), image: './product.jpg', price: 99.99, type:['红色','绿色','蓝色'], status:1});
            }

            //成功后执行以下操作
            for(let d of dataArr) {
                d.endTime = currentMiaoSha.value.expireTime;
                d.miaoShaId = currentMiaoSha.value.id;
                productArr.value.push(d);
            }
            pages.value = 5;
            productLoading.value = false;
            noMoreData.value = currentPageNum.value >= pages.value;
        }, 1000);
    } else {
        //请求api
        getProductsByMiaoShaIdFun(params.miaoShaId, params.pageNum, params.pageSize).then((result)=>{
            console.log('getProductsByMiaoShaIdFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);

                let data = result.data;
                //成功后执行以下操作
                for(let d of data.list) {
                    d.endTime = currentMiaoSha.value.expireTime;
                    d.miaoShaId = currentMiaoSha.value.id;
                    productArr.value.push(d);
                }
                pages.value = data.pages;
                noMoreData.value = currentPageNum.value >= pages.value;
            } else {
                DlMessageBox.error(result.msg);
            }
            productLoading.value = false;
        });
    }
}

//秒杀计时显示
const endTimer = ref();//定时器
const expireTxt = ref('');//显示文本
function countDownTime() {//倒计时处理
    //剩余时间
    let t = currentMiaoSha.value.expireTime - Date.now();
    if(t <= 0) {//活动结束, 停止倒计时
        clearInterval(endTimer.value);
        expireTxt.value = `活动结束`;
        return;
    }
    //剩余时间 转换为 时分秒
    let h = Math.trunc(t / (60*60*1000));
    let m = Math.trunc( (t % (60*60*1000)) / (60*1000) );
    let s = Math.trunc( (t % (60*1000)) / 1000 );
    if(m < 10) m = '0'+m;
    if(s < 10) s = '0'+s;
    expireTxt.value = `活动倒计时: ${h}:${m}:${s}`;
}

//购物车
const cart = inject('cart');
//加入购物车
function doAddCart(product) {
    if(!isLogin.value) {
        DlMessageBox.error('您还未登录,\n请先登录!');
        return;
    }
    //console.log(product.endTime);

    if (window && window.enableDl) {
        //模拟
        if(cart[product.id]){
            cart[product.id].num++;
        } else {
            cart[product.id] = {
                productId: product.id, 
                image: product.image, 
                title: product.title, 
                price: product.price, 
                type: product.type, 
                num: 1, checked: false, 
                endTime: product.endTime,
                miaoShaId: product.miaoShaId,
            };
        }
        console.log(cart[product.id]);
        //成功后执行以下操作
        DlMessageBox.success('加入成功');
        //console.log('cart:', cart);
    } else {
        //请求api
        addToCartFun(product.id, product.miaoShaId).then((result)=>{
            console.log('result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//前往详情页
function goDetail(product) {
    //详情页需要 productId
    localStorage.setItem('detailProductId', product.id);
    menuCore.push('/detail');
}

//滚动事件
function doChangeScroll(e) {
    let t = e.target;
    //回到顶部按钮处理, 显示与隐藏
    showTopBtn.value = t.scrollTop > showHideTop;

    let offsetNum = 10;//误差值
    let height = t.scrollHeight - t.offsetHeight - t.scrollTop - offsetNum;
    // 到底加载更多
    if(height <= 0) {
        console.log('滚动到底部了...');
        //如果还有数据,则加载;如果正在加载中,则不再执行
        if(!productLoading.value && currentPageNum.value < pages.value) {
            currentPageNum.value++;
            doLoadProductData();
        }
    }
}

//回到顶部
const viewRef = ref();
const showTopBtn = ref(false);
const showHideTop = 300;//隐藏和显示的scrollTop
const showAllRightMenu = ref(true);//显示和隐藏右侧所有菜单
const topBtnStyle = computed(()=>{
    let bottom = 1;
    let right = -1.8;
    if(showTopBtn.value) {
        right = 0.6;
    }
    return {bottom: bottom+'rem', right: right+'rem'};
});
function doGoTop() {
    if(viewRef.value) {
        viewRef.value.scrollTo({top: 0, behavior: 'smooth'});
    }
}
//去购物车
function doGoCartView() {
    menuCore.push('/cart');
}
//去home
function doGoHomeView() {
    menuCore.push('/home');
}
//去我的
function doGoUserView() {
    menuCore.push('/user');
}

//登录用户缓存
const loginUser = inject('loginUser');
const isLogin = ref(false);
function doCheckLogin() {
    if(!loginUser.value || !loginUser.value.token) {
        //页面可临时操作
        //menuCore.push('/login');
        return;
    }
    isLogin.value = true;
}

onMounted(()=>{
    doCheckLogin();
    doLoadMiaoShaData();
});

</script>
<template>
    <div class="view-dl" ref="viewRef" @scroll="doChangeScroll">
        <div class="top-head-dl">
            <IconArrowLeft class="back-icon" @click="doGoBack" />
            <div class="title-dl">限时秒杀</div>
        </div>
        <div class="view-body-dl" v-show="!msLoading" >
            <div class="miao-sha-type-box-dl" >
                <div class="miao-sha-type-list-dl" ref="miaoShaListRef" @scroll="doMiaoShaListScroll">
                    <template v-for="(m,i) in miaoShaArr" :key="m.id" >
                        <div class="maio-sha-title-dl" :class="m.selected?'ms-active-dl':''" @click="doSelectMiaoSha(m, i)" >{{m.name}}</div>
                    </template>
                </div>
                <div class="left-dl">
                    <IconCaretLeft class="icon-dl" @click="doMoveLeft" />
                </div>
                <div class="right-dl">
                    <IconCaretRight class="icon-dl" @click="doMoveRight" />
                </div>
            </div>

            <!-- 计时显示 -->
            <div class="expired-box-dl">
                <div class="expired-txt-dl">{{expireTxt}}</div>
            </div>

            <div class="product-list-dl" v-show="currentPageNum > 1 || !productLoading">
                <template v-for="p in productArr" :key="p.id" >
                    <ProductBox class="pro-dl" :product="p" @go-detail="goDetail" @add-cart="doAddCart" />
                </template>
            </div>

            <!-- noMoreData -->
            <div class="load-box-dl" >
                <DlLoading style="font-size: 1rem;" v-show="productLoading" />
                <div class="no-more-data-dl" v-show="!productLoading && noMoreData" >暂无更多活动商品</div>
            </div>
        </div>

        <div class="load-box-dl" v-show="msLoading" >
            <DlLoading style="font-size: 1rem;" />
        </div>

        <!-- 回到顶部 -->
        <div class="top-btn-dl" :style="topBtnStyle">
            <!-- <IconTopCircle class="icon-dl" @click="doGoTop" /> -->

            <div class="menu-list-dl" :style="'height:'+ (showAllRightMenu?'5.6':'0') +'rem;'">
                <IconHomeAlt class="icon-dl" @click="doGoHomeView" />
                <IconCart class="icon-dl" @click="doGoCartView" />
                <IconUser class="icon-dl" @click="doGoUserView" />
                <IconTopCircle class="icon-dl" @click="doGoTop" />
            </div>
            
            <IconTriangleDown v-if="showAllRightMenu" class="icon-dl" @click="showAllRightMenu=false" />
            <IconTriangleUp v-else class="icon-dl" @click="showAllRightMenu=true" />

        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    height: 100%;
    overflow: hidden auto;
}
.top-head-dl {
    background-color: #fff;
    color: #333;
    padding: 0.2rem;
    position: sticky;
    top: 0;
    z-index: 2;
}
.top-head-dl .back-icon {
    width: 0.8rem;
    height: 0.8rem;
    cursor: pointer;
    position: absolute;
    top: 50%;
    left: 0.2rem;
    transform: translate(0, -50%);
}
.top-head-dl .title-dl {
    font-size: 0.7rem;
    text-align: center;
}

.view-body-dl {
    margin: 0.2rem 0;
}

.miao-sha-type-box-dl {
    background-color: #fff;
    position: relative;
    padding: 0 0.6rem;
    user-select: none;
    min-height: 0.885rem;
}
.miao-sha-type-list-dl {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    position: relative;
}
.maio-sha-title-dl {
    flex-shrink: 0;
    padding: 0.16rem 0.2rem;
    cursor: pointer;
    border-right: 1px solid #ccc;
}
.maio-sha-title-dl:last-child {
    border-right: none;
}
.miao-sha-type-list-dl .ms-active-dl {
    background-color: #009dff;
    color: #fff;
}

.left-dl {
    position: absolute;
    left: -0.1rem;
    top: 50%;
    transform: translateY(-50%);
}
.left-dl .icon-dl {
    width: 0.8rem;
    height: 0.8rem;
    display: block;
}
.right-dl {
    position: absolute;
    right: -0.1rem;
    top: 50%;
    transform: translateY(-50%);
}
.right-dl .icon-dl {
    width: 0.8rem;
    height: 0.8rem;
    display: block;
}

.expired-box-dl {
    margin: 0.2rem;
}
.expired-txt-dl {
    font-size: 0.36rem;
    color: #f00;
    font-weight: bold;
}

.product-list-dl {
    margin: 0.2rem;
    padding: 0.2rem;
    background-color: #fff;
    border-radius: 0.2rem;
    display: grid;
    grid-template-columns: 1fr 1fr;
    justify-items: center;
    min-height: 2rem;
}
.pro-dl {
    font-size: 2.2rem;
}


.load-box-dl {
    text-align: center;
    color: #aaa;
    margin: 0.6rem 0;
}

.top-btn-dl {
    position: fixed;
    transition: all 0.2s linear;
    width: 1.4rem;
    font-size: 0;
}
.top-btn-dl .icon-dl {
    width: 1.4rem;
    height: 1.4rem;
    color: #fff;
    background-color: #999c;
    border-radius: 50%;
    cursor: pointer;
}
.menu-list-dl {
    transition: all 0.4s linear;
    overflow: hidden;
}

</style>